﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Rabbit.Logic;
using RabbitManage.Code;
using Raven.Imports.Newtonsoft.Json;

namespace RabbitManage.Action
{
    public partial class ShipRuleAdd : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies[Constant.CookieName];
            string shopId = cookie.Values[Constant.CookieUid];

            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            if (!string.IsNullOrEmpty(postContent))
            {
                try
                {
                    List<RegionCost> items = JsonConvert.DeserializeObject<List<RegionCost>>(postContent);

                    ShipRule rule = RabbitUse.GetShipRuleByShopId(Db.Store, shopId);
                    if (rule == null)
                    {
                        rule = new ShipRule();
                        rule.ShopId = shopId;
                        rule.Rules = new Dictionary<string, decimal>();
                    }

                    foreach (var item in items)
                    {
                        rule.Rules[item.Region] = item.Cost;
                    }
                    
                    RabbitUse.AddShipRule(Db.Store, rule);

                    //item.ShopId = shopId;

                    //string id = Request["id"];
                    //if (!string.IsNullOrEmpty(id))
                    //{
                    //    item.Id = id;
                    //}

                    //RabbitUse.AddDiliveryStrategy(Db.Store, item);

                    Response.Write("true");
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            else
            {
                Response.Write("false");
            }
        }
    }
}